#include "register.h"

//数据库字段
static db_col info[] =
{
  {"ACCOUNT", DB_STR, sizeof(char) * 6},
  {"PASSWD", DB_STR, sizeof(char) * 6},
  {"EMAIL", DB_STR, sizeof(char) * 20},
  {nullptr, 0, 0},
};

Register::Register()
{
  tablename_ = "ACCOUNTTABLE";
  conf_file_ = "/config.xml";
  mq_ = nullptr;
}

Register::~Register()
{

}


bool Register::loadConfig()
{
  qXmlParse xml;
  if(!xml.initFile(conf_path_ + conf_file_))
  {
    LOG_ERROR("FFL[%s:%s:%d] init file fail %s", LOG_FFL, conf_file_.c_str());
    return false;
  }

  xmlNodePtr rootNode = xml.getRootNode();
  if(!rootNode)
  {
    LOG_ERROR("FFL[%s:%s:%d]  fail %s", LOG_FFL, conf_file_.c_str());
    return false;
  }

  xmlNodePtr logNode = xml.getChildNode(rootNode, "LogFile");
  if(logNode)
  {
    xml.getNodePropStr(logNode, "logfilename", logfile_name_);
  }
  
  xmlNodePtr mysqlNode = xml.getChildNode(rootNode, "MysqlInfo");
  if(mysqlNode)
  {
    xml.getNodePropStr(mysqlNode, "url", sqlurl_);
  }
 
  return true;
}

#define CURPATH_MAX 1024
bool Register::init()
{
  char path_buff[CURPATH_MAX] = { 0  };
  char* ret = getcwd(path_buff, CURPATH_MAX);
  if(!ret)
  {
    return false;
  }
  cur_path_.clear();
  cur_path_ = path_buff;
  conf_path_ = cur_path_ + "/wwwroot/homepage/login/src";
  logpath_ = cur_path_ + "/../log/";  
  
  if(!loadConfig())
  {
    return false;
  }
  logpath_ = logpath_ + logfile_name_;

  COM::logger = new qLogger(logpath_);
  mq_ = MysqlConnPool::getInstance();
  mq_->init(sqlurl_.c_str());



  return true;
}



bool Register::parseParam(std::string param, std::string& account, std::string& passwd, std::string& email)
{
  std::cerr << "param: " << param <<std::endl;
  //{ username: username, password: password, email: email  }
  size_t pos = param.find(',');
  if(pos == std::string::npos)
  {
    return false;
  }

  account = param.substr(0, pos);
  std::string sub_param = param.substr(pos + 1);

  pos = account.find(':');
  if(pos == std::string::npos)
  {
    return false;
  }

  account = account.substr(pos + 2);
  account.pop_back();

  pos = sub_param.find(',');
  if(pos == std::string::npos)
  {
    return false;
  }
  passwd = sub_param.substr(0, pos);
  email = sub_param.substr(pos + 1);
  pos = passwd.find(':');
  if(pos == std::string::npos)
  {
    return false;
  }

  passwd = passwd.substr(pos + 2);
  passwd.pop_back();

  pos = email.find(':');
  if(pos == std::string::npos)
  {
    return false;
  }
  email = email.substr(pos + 2);
  email.pop_back();
  email.pop_back();

  return true;
}

picojson::value Register::structToJson(const respData& resp)
{
  picojson::object obj;
  obj["success"] = picojson::value(resp.success_);
  obj["message"] = picojson::value(resp.message_);
  return picojson::value(obj);
}

bool Register::registerUser()
{
  respData resp;
  //获得方法
  char* m = getenv("METHOD_ENV"); 
  if(strcasecmp(m, "POST") != 0)
  {
    resp.success_ = false;
    resp.message_ = "method not post";
  }

  //获得参数
  UserInfo* u = nullptr;
  char parambuf[1024] = { 0 };
  ssize_t s = read(0, parambuf, 1024);
  if(s > 0)
  {
    parambuf[s] = '\0';
    //分解参数
    std::string account;
    std::string passwd;
    std::string email;
    Connid connid = 0;

    char where[128] = { 0 };
    if(!parseParam(parambuf, account, passwd, email))
    {
      resp.success_ = false;
      resp.message_ = "param error";
      goto END;
    }
    if(account.empty() || passwd.empty() || email.empty())
    {
      resp.success_ = false;
      resp.message_ = "data error";
      goto END;
    }
    std::cerr << "username:" << account << " passwd:" << passwd << "email:" << email << std::endl;

    if(account.size() >= ACCOUNT_LEN || passwd.size() >= PASSWD_LEN || email.size() >= EMAIL_LEN)
    {
      resp.success_ = false;
      resp.message_ = "data size is too long";
      goto END;
    }

    sprintf(where, "`ACCOUNT`='%s'", account.c_str());
    connid = mq_->getHandle(nullptr);
    //查数据库, 是否存在
    if(mq_->exeSelect(connid, tablename_.c_str(), info, where, nullptr, nullptr, (unsigned char**)&u) >= 0)
    {
      resp.success_ = false;
      resp.message_ = "exist account";
      goto END;
    }
    if(u)
    {
      resp.success_ = false;
      resp.message_ = "exit message";
      goto END;
    }

    //不存在 插入
    u = new UserInfo;
    memcpy(u->account_, account.c_str(), account.size() + 1); 
    memcpy(u->passwd_, passwd.c_str(), passwd.size() + 1); 
    memcpy(u->email_, email.c_str(), email.size() + 1); 
    std::cerr << "----------" << " 11 username:" << u->account_ << " passwd:" << u->passwd_ << " email:" << u->email_ << std::endl;
    if(mq_->exeInsert(connid, tablename_.c_str(), info, (const unsigned char*)u) < 0)
    {
      resp.success_ = false;
      resp.message_ = "insert fail";
      goto END;
    }
  }
  else 
  {
    resp.success_ = false;
    resp.message_ = "no param";
  }

END:
  if(u)
    delete u;

  picojson::value jsonValue = structToJson(resp);
  std::string jsonStr = jsonValue.serialize();
  write(1, jsonStr.c_str(), jsonStr.size());

  return true;
}

